package com.collect.tanzania.zhiScene.zhiDs.zhiFollow;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.collect.tanzania.R;
import com.collect.tanzania.zhiAdater.zhiDs.ZHIDsListAdjuster;
import com.collect.tanzania.zhiBase.BaseFragment;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRDsEntity;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRDsListEntity;
import com.collect.tanzania.zhiBean.zhiSend.ZHISAuditerReviewMarkedOrder;
import com.collect.tanzania.zhiBean.zhiSend.ZHISDsMarkedOrder;
import com.collect.tanzania.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.tanzania.zhiHelper.ZHIDsHelper;
import com.collect.tanzania.zhiHelper.ZHISysShareHelper;
import com.collect.tanzania.zhiScene.zhiDs.zhiRoot.ZHIRootDsFragmentInterface;
import com.collect.tanzania.zhiScene.zhiWidget.zhiDialog.ZHIDialogItemClickListener;
import com.collect.tanzania.zhiScene.zhiWidget.zhiDialog.ZHIDialogWordsInput;
import com.collect.tanzania.zhiUtils.ToastUtil;

import java.util.ArrayList;

import butterknife.BindView;

@SuppressLint("NonConstantResourceId")
public class ZHIDsFollowFragment extends BaseFragment<ZHIDsFollowPresenter> implements ZHIDsFollowContract.View {

    @BindView(R.id.srl_swipe_layout)
    SwipeRefreshLayout srl_swipe_layout;

    @BindView(R.id.rc_list)
    RecyclerView rc_list;

    @BindView(R.id.tv_page_title_history)
    TextView tv_page_title_history;

    private ZHIRootDsFragmentInterface mZHIRootDsFragmentInterface;

    private final ZHIDsListAdjuster mZHIDsListAdjuster = new ZHIDsListAdjuster();

    private String mNameMatchFlag = "";

    private final ArrayList<ZHIRDsEntity> mOrderList = new ArrayList<>();

    @Override
    protected void initInjector() {
        mFragmentComponent.inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_follow_ds;
    }

    @Override
    protected void initView(View view) {
        try {
            srl_swipe_layout.setColorSchemeColors(getResources().getColor(R.color.theme_color_0));
            initEvent();
            initData(true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mZHIRootDsFragmentInterface = (ZHIRootDsFragmentInterface) activity;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onGetErrorInfo() {
        srl_swipe_layout.setRefreshing(false);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onGetLatestDsList(ZHIRDsListEntity zhirDsListEntity) {
        try {
            srl_swipe_layout.setRefreshing(false);

            mOrderList.clear();
            mOrderList.addAll(zhirDsListEntity.getList());
            mZHIDsListAdjuster.setNewData(mOrderList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onMarkDsOrder(boolean isSelf) {
        ZHIDsHelper.LAST_DS_CALL_TIME = System.currentTimeMillis();
        if (isSelf) {
            for (int i = 0; i < mOrderList.size(); i++) {
                ZHIRDsEntity item = mOrderList.get(i);
                item.setNameMatchFlag("YES");
            }
            mZHIDsListAdjuster.notifyDataSetChanged();
        } else {
            initData(true);
        }
    }

    @SuppressLint({"InflateParams", "NotifyDataSetChanged"})
    public void initEvent() {
        try {
            srl_swipe_layout.setOnRefreshListener(() -> initData(false));
            mZHIDsListAdjuster.setEmptyView(getRefreshEmptyView());
            rc_list.setLayoutManager(new GridLayoutManager(this.getActivity(), 1));
            rc_list.setAdapter(mZHIDsListAdjuster);

            mZHIDsListAdjuster.setOnDsItemClickListener((zhirDsEntity, actionType) -> {
                if (ZHIDsActionType.COPY_MOBILE.equalsIgnoreCase(actionType)) {
                    //电话操作
                    ZHISysShareHelper.copyToClipboard(getActivity(), zhirDsEntity.getMobile());

                } else if (ZHIDsActionType.CALL_PHONE_SELF.equalsIgnoreCase(actionType)) {
                    //电话操作
                    ZHISysShareHelper.callPhone(getActivity(), zhirDsEntity.getMobile(), (zhirDsEntity.getMobile().length() <= 9));

                } else if (ZHIDsActionType.CALL_PHONE.equalsIgnoreCase(actionType)) {
                    //电话操作
                    ZHISysShareHelper.callPhone(getActivity(), zhirDsEntity.getContactMobile(), (zhirDsEntity.getContactMobile().length() <= 9));

                } else if (ZHIDsActionType.CALL_WHATSAPP.equalsIgnoreCase(actionType)) {
                    //whatsapp操作
//                    ZHISysShareHelper.sendMsgWithWhatsApp(getActivity(), ZHIProjectConfigs.PRE_PHONE + zhirDsEntity.getContactMobile(), "");
                    Log.d(TAG, "initEvent: whatsapp");

                } else if (ZHIDsActionType.RESULT_NAME_MATCH.equalsIgnoreCase(actionType)) {
                    //姓名匹配操作
                    mNameMatchFlag = ZHIDsActionType.RESULT_NAME_MATCH;

                    for (int i = 0; i < mOrderList.size(); i++) {
                        ZHIRDsEntity item = mOrderList.get(i);
                        item.setNameMatchFlag("YES");
                    }
                    mZHIDsListAdjuster.notifyDataSetChanged();

                } else if (ZHIDsActionType.RESULT_NAME_NOT_MATCH.equalsIgnoreCase(actionType)) {
                    //姓名不匹配操作
                    mNameMatchFlag = ZHIDsActionType.RESULT_NAME_NOT_MATCH;

                    for (int i = 0; i < mOrderList.size(); i++) {
                        ZHIRDsEntity item = mOrderList.get(i);
                        item.setNameMatchFlag("YES");
                    }
                    mZHIDsListAdjuster.notifyDataSetChanged();

                } else if (ZHIDsActionType.RESULT_NO_ANSWER.equalsIgnoreCase(actionType)) {
                    //标记操作
                    //判断是否已打电话
                    if (!checkCallResult(zhirDsEntity.getContactMobile(), ZHIDsActionType.RESULT_NO_ANSWER)) {
                        return;
                    }
                    if (mPresenter != null) {
                        ZHISDsMarkedOrder zhisDsMarkedOrder = new ZHISDsMarkedOrder(zhirDsEntity.getOrderId(), ZHIDsActionType.RESULT_NO_ANSWER, ZHIDsActionType.REMARK_NO_ANSWER, zhirDsEntity.getContactMobile(), mNameMatchFlag, false);
//                        mPresenter.markDsOrder(getActivity(), zhisDsMarkedOrder, true, false);
                        showRemarkDialog(zhisDsMarkedOrder, false);

                    }

                } else if (ZHIDsActionType.RESULT_KNOW_USER.equalsIgnoreCase(actionType)) {
                    //标记操作
                    //判断是否已打电话
                    if (!checkCallResult(zhirDsEntity.getContactMobile(), ZHIDsActionType.RESULT_KNOW_USER)) {
                        return;
                    }
                    if (mPresenter != null) {
                        ZHISDsMarkedOrder zhisDsMarkedOrder = new ZHISDsMarkedOrder(zhirDsEntity.getOrderId(), ZHIDsActionType.RESULT_KNOW_USER, ZHIDsActionType.REMARK_KNOW_USER, zhirDsEntity.getContactMobile(), mNameMatchFlag, false);
//                        mPresenter.markDsOrder(getActivity(), zhisDsMarkedOrder, true, false);
                        showRemarkDialog(zhisDsMarkedOrder, false);

                    }

                } else if (ZHIDsActionType.RESULT_NOT_KNOW_USER.equalsIgnoreCase(actionType)) {
                    //标记操作
                    //判断是否已打电话
                    if (!checkCallResult(zhirDsEntity.getContactMobile(), ZHIDsActionType.RESULT_NOT_KNOW_USER)) {
                        return;
                    }
                    if (mPresenter != null) {
                        ZHISDsMarkedOrder zhisDsMarkedOrder = new ZHISDsMarkedOrder(zhirDsEntity.getOrderId(), ZHIDsActionType.RESULT_NOT_KNOW_USER, ZHIDsActionType.REMARK_NOT_KNOW_USER, zhirDsEntity.getContactMobile(), mNameMatchFlag, false);
//                        mPresenter.markDsOrder(getActivity(), zhisDsMarkedOrder, true, false);
                        showRemarkDialog(zhisDsMarkedOrder, false);

                    }
                } else if (ZHIDsActionType.RESULT_ABNORMAL_NUMBER_CONTACT.equalsIgnoreCase(actionType)) {
                    //标记操作
                    //判断是否已打电话
                    if (!checkCallResult(zhirDsEntity.getContactMobile(), ZHIDsActionType.RESULT_ABNORMAL_NUMBER_CONTACT)) {
                        return;
                    }
                    if (mPresenter != null) {
                        ZHISDsMarkedOrder zhisDsMarkedOrder = new ZHISDsMarkedOrder(zhirDsEntity.getOrderId(), ZHIDsActionType.RESULT_ABNORMAL_NUMBER_CONTACT, ZHIDsActionType.RESULT_ABNORMAL_NUMBER, zhirDsEntity.getContactMobile(), mNameMatchFlag, false);
//                        mPresenter.markDsOrder(getActivity(), zhisDsMarkedOrder, true, false);
                        showRemarkDialog(zhisDsMarkedOrder, false);

                    }
                } else if (ZHIDsActionType.RESULT_ABNORMAL_NUMBER_SELF.equalsIgnoreCase(actionType)) {
                    mNameMatchFlag = ZHIDsActionType.RESULT_ABNORMAL_NUMBER_SELF;

                    //标记操作
                    //判断是否已打电话
                    if (!checkCallResult(zhirDsEntity.getMobile(), ZHIDsActionType.RESULT_ABNORMAL_NUMBER_SELF)) {
                        return;
                    }
                    if (mPresenter != null) {
                        ZHISDsMarkedOrder zhisDsMarkedOrder = new ZHISDsMarkedOrder(zhirDsEntity.getOrderId(), ZHIDsActionType.RESULT_ABNORMAL_NUMBER_SELF, ZHIDsActionType.RESULT_ABNORMAL_NUMBER, zhirDsEntity.getMobile(), mNameMatchFlag, true);
//                        mPresenter.markDsOrder(getActivity(), zhisDsMarkedOrder, true, true);
                        showRemarkDialog(zhisDsMarkedOrder, true);
                    }
                }
            });

            tv_page_title_history.setOnClickListener(view -> ZHIProjectRouter.toDsFollowHistory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initData(boolean showLoading) {
        if (mPresenter != null) {
            mPresenter.getLatestDsList(getActivity(), showLoading);
        }
    }

    private void showRemarkDialog(ZHISDsMarkedOrder zhisDsMarkedOrder, boolean isSelf) {
        ZHIDialogWordsInput.showDialog(requireActivity(), "", getString(R.string.pls_enter), getString(R.string.btn_cancel), getString(R.string.confirm), false, new ZHIDialogItemClickListener() {
            @Override
            public void onConfirmClick(String content) {
                try {
                    if (mPresenter != null) {
                        zhisDsMarkedOrder.setContent(content);
                        mPresenter.markDsOrder(getActivity(), zhisDsMarkedOrder, true, isSelf);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancelClick() {

            }
        });
    }

    private View getRefreshEmptyView() {
        View emptyView = getLayoutInflater().inflate(R.layout.view_empty_no_data, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        emptyView.setOnClickListener(v -> {
            initData(true);
        });
        return emptyView;
    }

    private boolean checkCallResult(String mobile, String actionType) {
        int result = ZHIDsHelper.getInstance().checkCallRecord(mobile);
        if (ZHIDsHelper.RESULT_CALL_SUCCESS == result) {
            return true;
        }
        if (ZHIDsHelper.RESULT_UNVALID_MOBILE == result) {
            if (ZHIDsActionType.RESULT_NO_ANSWER.equalsIgnoreCase(actionType)) {
                return true;
            }
            if (ZHIDsActionType.RESULT_ABNORMAL_NUMBER_CONTACT.equalsIgnoreCase(actionType)) {
                return true;
            }
            if (ZHIDsActionType.RESULT_ABNORMAL_NUMBER_SELF.equalsIgnoreCase(actionType)) {
                return true;
            }
        }
        if (ZHIDsHelper.RESULT_CALL_DURATION_IS_ZERO == result) {
            if (ZHIDsActionType.RESULT_NO_ANSWER.equalsIgnoreCase(actionType)) {
                return true;
            }
            if (ZHIDsActionType.RESULT_ABNORMAL_NUMBER_CONTACT.equalsIgnoreCase(actionType)) {
                return true;
            }
            if (ZHIDsActionType.RESULT_ABNORMAL_NUMBER_SELF.equalsIgnoreCase(actionType)) {
                return true;
            }
        }
        ToastUtil.s("Is this really the case? Please take work seriously-" + result);
        return false;
    }

    public void refreshData() {
        initData(true);
    }

}